package com.jia.together.controller;


import com.jia.together.entity.User;
import com.jia.together.entity.User;
import com.jia.together.service.UserService;
import com.jia.together.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dujiajia
 * @since 2021-02-19
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody User user){
        String token = userService.easyLogin(user);
        return R.ok().data("token",token);
    }

    @PostMapping("/add")
    public R add(@RequestBody User user) {

        String password = user.getPassword();
        String newPassword = passwordEncoder.encode(password);
        User saveUser = new User();
        BeanUtils.copyProperties(user,saveUser);
        saveUser.setPassword(newPassword);
        userService.save(saveUser);
        return R.ok();
    }
    @GetMapping("/info/{id}")
    public R inf(@PathVariable String id){
        User user = userService.getById(id);
        return R.ok().data("data",user);
    }

    @GetMapping("/list")
    public R list(@RequestParam Long pageNum,@RequestParam Long pageSize) {
        Map<String,Object> map = userService.selectPageList(pageNum,pageSize);
        return R.ok().data(map);
    }

    @PutMapping("/update")
    public R update(@RequestBody User user){
        String password = user.getPassword();
        String newPassword = passwordEncoder.encode(password);
        User saveUser = new User();
        BeanUtils.copyProperties(user,saveUser);
        saveUser.setPassword(newPassword);
        userService.updateById(saveUser);
        return R.ok();
    }
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable String id){
        userService.removeById(id);
        return R.ok();
    }
    
    @GetMapping("/getInfoByToken")
    public R getInfoByToken(HttpServletRequest request) {
        User user = userService.selectInfoByToken(request);
        return R.ok().data("data",user);
    }
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) throws ServletException {
        request.logout();
        return R.ok();
    }
}

